<?php
/*
Plugin Name: it-ebooks
Plugin URI: http://www.hengha.info
Description: Crawl books from http://www.it-ebooks.info
Version: 1.0
Author: tomcat
Author URI: http://www.hengha.info
Text Domain: it-ebooks
Domain Path: /languages/
*/

require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
require_once("qiniu/io.php");
require_once("qiniu/http.php");
require_once("qiniu/rs.php");

function cron_add_small_interval($schedules)
{
    if (!isset($schedules['ten-minutes'])) {
        $schedules['ten-minutes'] = array(
            'interval' => 600,
            'display' => __('Ten Minutes', 'qiushibaike')
        );
    }
    if (!isset($schedules['three-minutes'])) {
        $schedules['three-minutes'] = array(
            'interval' => 180,
            'display' => __('Three Minutes', 'qiushibaike')
        );
    }

    return $schedules;
}

add_filter('cron_schedules', 'cron_add_small_interval');

function prefix_activation()
{
    wp_schedule_event(time(), 'hourly', 'books_hour_event_hook');
    wp_schedule_event(time(), 'three-minutes', 'books_three_minutes_event_hook');
    wp_schedule_event(time(), 'ten-minutes', 'books_ten_minutes_event_hook');
}

register_activation_hook(__FILE__, 'prefix_activation');
function books_compare_category($a, $b)
{
    if ($a->extra->last_check == $b->extra->last_check) {
        return 0;
    }
    return $a->extra->last_check < $b->extra->last_check ? 1 : -1;
}

function books_get_all_tags()
{
    $progress = array();
    $finished = array();
    $empty_extra = (object)array('last_check' => 0, 'page' => 1, 'total' => 0);
    foreach (get_categories(array('taxonomy' => 'book_tag', 'hide_empty' => false)) as $category) {
        $cat = clone $category;
        $extra = null;
        if ($cat->description) {
            $extra = json_decode($cat->description);
        }
        if (!$extra) {
            $extra = $empty_extra;
        }
        $cat->extra = $extra;

        if ($cat->extra->page > $cat->extra->total) {
            $finished[] = $cat;
        } else {
            $progress[] = $cat;
        }
    }

    usort($progress, 'books_compare_category');
    usort($finished, 'books_compare_category');
    return array('progress' => $progress, 'finished' => $finished);
}

function books_get_the_tag()
{
    $tags = books_get_all_tags();
    if (count($tags['progress']) > 0) {
        return $tags['progress'][0];
    }
    if (count($tags['finished']) > 0) {
        return $tags['finished'][0];
    }
    return null;
}

function books_get_user_id($name)
{
    $login = str_replace(array('.', ' ', '-'), '_', strtolower($name));
    $userId = username_exists($login);
    if ($userId == null) {
        $userId = wp_insert_user(array(
            'display_name' => $name,
            'user_login' => $login,
            'user_email' => $login . '@it-ebooks.info',
            'user_pass' => wp_generate_password(20),
            'role' => 'subscriber'
        ));
    }
    return $userId;
}

function books_upload_images($urls)
{
    $bucket = "tuicool";
    $accessKey = '6bN1rBfJxUCffyALboGIIsjAqy6cZuBe1TUfEkXy';
    $secretKey = 'Q2g47GmzAF9ydbw2-2VpgqACWarj3B1GSprupY2E';

    Qiniu_SetKeys($accessKey, $secretKey);
    $putPolicy = new Qiniu_RS_PutPolicy ($bucket);
    $upToken = $putPolicy->Token(null);
    $putExtra = new Qiniu_PutExtra ();
    $putExtra->Crc32 = 1;
    $images = array();
    foreach ($urls as $key => $url) {
        $file_name = substr($url, strrpos($url, '/') + 1);
        $data = file_get_contents($url);
        list ($ret, $err) = Qiniu_Put($upToken, $file_name, $data, $putExtra);

        if ($err !== null) {
            error_log(json_encode($err));
        } else {
            $images[$url] = 'http://tuicool.qiniudn.com/' . $ret['key'];
        }
    }
    return $images;
}

function books_check_book()
{
    $args = array('post_type' => 'book', 'posts_per_page' => 1, 'paged' => 1, 'post_status' => 'draft');
    $q = new WP_Query($args);
    if ($q->have_posts()) {

    }
}

function books_check_images()
{
    $args = array(
        'post_type' => 'book',
        'posts_per_page' => 10,
        'paged' => 1,
        'meta_key' => 'new_image',
        'meta_value' => '#'
    );
    $q = new WP_Query($args);
    $urls = array();

    if ($q->have_post()) {
        foreach ($q->posts as $post) {
            $urls[$post->ID] = get_post_meta($post->ID, 'image', true);
        }
        $images = books_upload_images($urls);
        foreach ($images as $id => $image) {
            update_post_meta($id, 'new_image', $image);
        }
    }
}

function books_search()
{
    $host = 'http://it-ebooks-api.info/v1';
    $args = array('user-agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; LENW8)',
        'httpversion' => '1.1',
        'timeout' => 120);
    $tag = books_get_the_tag();
    if (!$tag) {
        error_log("can't find available");
        return;
    }
    $url = sprintf("/search/%s/page/%d", urlencode($tag->name), $tag->extra->page);
    $content = wp_remote_get($host . $url, $args);
    if (is_wp_error($content)) {
        error_log(sprintf("request %s failed", $url));
        return;
    }
    $model = json_decode($content['body']);
    if ($model->Error != 0) {
        error_log(sprintf("occur error when request %s", $url));
        exit;
    }
    $tag->extra->total = $model->Total;
    $tag->extra->page = intval($model->Page) + 1;
    $tag->extra->last_check = time();
    $tag->description = json_encode($tag->extra);
    wp_insert_category((array)$tag);
    $args = array('post_type' => 'book', 'posts_per_page' => 1, 'paged' => 1, 'meta_key' => 'book_id');
    foreach ($model->Books as $book) {
        $args['meta_value'] = $book->ID;
        $q = new WP_Query($args);
        if (!$q->has_posts()) {
            $post_id = wp_insert_post(array(
                'post_title' => $book->Title,
                'post_content' => $book->Description,
                'post_status' => 'draft',
                'post_type' => 'book',
                'tags_input' => $tag->name
            ));
            add_post_meta($post_id, 'isbn', $book->isbn, true);
            add_post_meta($post_id, 'book_id', $book->ID, true);
            add_post_meta($post_id, 'sub_title', $book->SubTitle, true);
            add_post_meta($post_id, 'image', $book->Image, true);
            add_post_meta($post_id, 'new_image', '#', true);
        }
    }
}

add_action('books_hour_event_hook', 'books_search');
add_action('books_three_minutes_event_hook', 'books_check_images');
add_action('books_ten_minutes_event_hook', 'books_check_book');
function prefix_deactivation()
{
    wp_clear_scheduled_hook('books_hour_event_hook');
    wp_clear_scheduled_hook('books_three_minutes_event_hook');
    wp_clear_scheduled_hook('books_ten_minutes_event_hook');
}

register_deactivation_hook(__FILE__, 'prefix_deactivation');
?>
